import importlib
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
import pandas as pd
import pickle



def from_import(model, package):
    package = importlib.import_module(package)
    return getattr(package, model)


def get_model(model, package, **key):
    return from_import(model, package)(**key)


def metrics_calculate(model, X, Y, df=False):
    pred = model.predict(X)
    report = classification_report(Y, pred, output_dict=True)
    if df:
        return pd.DataFrame(report)
    else:
        return report


def train(model, X, Y,partial_fit=False):
    if partial_fit:
        model.partial_fit(X,Y)
    else:
        model.fit(X, Y)
    return model


def pretreatment(df,label=True,split=True,std=True,fillna=True):
    if label:
        features = df.iloc[:, 1:-1]
    else:
        features = df.iloc[:, 1:]
    numeric_features = features.dtypes[features.dtypes != 'object'].index
    if std:
        features[numeric_features] = (features[numeric_features] - features[numeric_features].mean()) / features[numeric_features].std()
    if fillna:
        features[numeric_features] = features[numeric_features].fillna(0)
    train_features = pd.concat([df[['sample_id']], features], axis=1)
    if label:
        train_label = df[['sample_id', 'label']]
        df = pd.concat([train_features, train_label[['label']]], axis=1)

        X = df.drop(['sample_id', 'label'], axis=1)
        Y = df[['label']]
        if split:
            x_train, x_test, y_train, y_test = train_test_split(
                X, Y, test_size=0.15, random_state=123, stratify=Y)
            return ((x_train, y_train), (x_test, y_test))
        else:
            return X,Y
    else:
        X = features
        return X
    
if __name__ == '__main__':
    traindf = pd.read_csv(r'data\train_10000.csv')
    testdf = pd.read_csv(r'data\test_2000_x.csv')
    validatedf = pd.read_csv(r'data\validate_1000.csv')
    traindata = pretreatment(traindf,split=False,std=False)
    testdata = pretreatment(testdf,label=False,std=False)
    validatedata = pretreatment(validatedf,split=False,std=False)
#     m = get_model("GradientBoostingClassifier","sklearn.ensemble",n_estimators=1000)
#     m = get_model("DecisionTreeClassifier","sklearn.tree")
#     df = pd.read_csv('./data/preprocess_train.csv')
#     traind,testd = pretreatment(df)
#     m = train(m,*traind)
#     print(metrics_calculate(m,*testd))
    # import pickle
    # with open('train_model.model', 'wb') as f:
    #     pickle.dump(m, f)
    